/**
 * Notations
 * this.[property/fn] : public
 * this._[property/fn] : protected
 * var _[property/fn] : private and static
 * this.__init => méthode de construction
 *
 * heritage palette
 * Pour creer une nouvelle palette: On crée sa classe que l'on fera hérité de PalettePlayer, les méthodes et prorpiétés public sont précédés de this afin d'éviter les associations
 * statique.
 * La méthodes de construct est __init(player, conf, scopeThis), cette méthodes est définie au début mais appelée en fin de classe. En parametre le player, la configuration de la palette, et l'objet en lui même qui sera transmis
 * à la superclass. Dans __init, toute les propriétés de l'objet seront définies, on appel également le __init() de la superclasse en faisant référence au prototype: this.constructor.prototype.__init(player, conf, this). On
 * fournie le scope qui aura l'héritage du parent (this dans [parent].__init faisant référence au parent prototype et non à l'enfant).
 * Pour la clarté, on défini une méthode non obligatoire bindEvent appelée dans le __init qui associe les événements au Player, on l'appel ou l'on veut en fonction de ses besoins et du cheminement de définition
 * @abstract
 * @param Player player
 * @param object conf
 */
var PalettePlayer = function(player, conf) {
    var _conf, _baseConf, _defaultConf;
    var _hammer;
    var self;

    _defaultConf = {};

    _conf = conf ? conf : _defaultConf;
    var _defaultClass = 'palette';

    this.parent = this;
    this.parent.name = 'palette';
    this.isShow = true;

    this.setPlayer = function (sPlayer) {
        self = this;
        if (!sPlayer instanceof Player) {
            alert('setPlayer doit fournir un object de type Player');
            return;
        }
        this._player = sPlayer;
    };

    this.getPlayer = function() {
        return this._player;
    };

    this.getDefaultClass = function() {
        return _defaultClass;
    };

    this.setHammer = function(hammer) {
        _hammer = hammer;
        return this;
    };

    this.getHammer = function() {
        return this._hammer;
    };

    this.show = function() {
        this.isShow = true;
        $(this.getDom()).show();
        return this;
    }

    this.hide = function() {
        this.isShow = false;
        $(this.getDom()).hide();
        return this;
    };

    this.getConf = function() {
        return this._conf;
    };

    this.getName = function() {
        return this.name;
    };

    /**
     * alpha
     */
    this.setActiveDragMove = function(active) {
        active = typeof active !== 'undefined' ? active : true;
        this._activeDragMove = active;
        var hammer;
        var el = this.getDom();
        if (!el) {
            console.log('élément non défini pour ' + this.getName());
        }
        hammer = new Hammer( el, {prevent_default: true, drag_vertical: true, swipe: false, drag_min_distance: 0} );
        if (active) {
            paletteDragable(hammer, $(this.getDom()));
        }
        return this;
    };

    this.getDragHandle = function() {
        return this._domHandle;
    };

    this.isActiveDragMove = function() {
        return this._activeDragMove;
    };

    this.getDom = function() {
        return this._dom;
    };

    this.render = function() {
        if (!this._player || this._isRender) {
            return this;
        }
        var container = this._player.getDom();
        var soDom = document.createElement('div');
        soDom.innerHTML = this._aDom.join("\r\n");
        this._dom = soDom.firstChild;
        delete soDom;
        container.appendChild(this._dom);
        $(this._dom).addClass(_defaultClass);
        var id;
        if (!this._dom.getAttribute('id')) {
            if (this._conf.id) {
                id = this._conf.id;
            } else if(this._conf.name) {
                id = $(container).attr('id') + '-' + this._conf.name;
            }
            if (id) {
                this._dom.setAttribute('id', id);
            }
        }

        if (this._conf.cls) {
            $(this._dom).addClass(this._conf.cls);
        }
        this._isRender = true;
        return this;
    };

    this.isRender = function() {
        return this._isRender;
    }

    this.init = function() {
        /*console.log('not working, just a test');
        console.log(this);*/

    };

    this.getMe = function() {return this;}

    this.__init = function(player, conf, _this) {
        var self              = _this;
        var _defaultConf      = {};
        _this                 = _this || this;
        _this._dom            = null;
        _this._conf           = conf ? conf : _defaultConf;
        _this._isRender       = false;
        _this._activeDragMove = false;
        _this._player         = null;
        _this.name            = _this._conf.name || _this.name;
        _this.self            = _this;
        _this._domHandle;
        _this.setPlayer(player);
        player.registerPalette(_this);
        return _this;
    };
};

/**
 * Méthode statique d'extend du parent PalettePlayer
 * @param Array/Object
 * @return void
 **/
PalettePlayer.extending = function(aPalettes) {
    aPalettes = (!aPalettes instanceof Array) ? [aPalettes] : aPalettes;
    var current;
    for (var cpt = 0; cpt < aPalettes.length; cpt++) {
        current = aPalettes[cpt];
        current.prototype = new PalettePlayer();
        current.prototype.constructor = current;
    }
    return;
};



var PaletteControls = function(player, conf) {
    var self = this;
    var _mouseTimer = 0;

    this.__init = function(player, conf, _this) {
        _this = _this || this;
        _this._aDom = [
            '<div id="palette-control" class="palette-control palette rounded pictosTransparents">',
                '<div class="drag-bar gradient-programme1"></div>',
                '<div class="btn-control-ctn">',
                '<ul>',
                    '<li class="gradient-programme1 btn btn-turnLeft"><div value="left" type="button"></div></li>',
                    '<li class="gradient-programme1 btn btn-turnRight"><div value="right" type="button"></div></li>',
                    '<li class="gradient-programme1 btn btn-zoomPlus"><div value="zoom+" type="button"></div></li>',
                    '<li class="gradient-programme1 btn btn-zoomMinus"><div value="zoom-" type="button"></div></li>',
                    '<li class="gradient-programme1 btn btn-toggleMove"><div value="togglemove" type="button"></div></li>',
                    '<li class="gradient-programme1 btn btn-fullscreen"><div value="fullscreen" type="button"></div></li>',
                '</ul>',
                '<div style="clear: both;">','</div>',
                '</div>',
            '</div>'

            /*'<div id="control" class="ui-widget-content palette rayures-inverses">',
                //'<div class="grip grip-gauche"></div>',
                //'<div class="grip grip-droite"></div>',
                '<h5></h5>',
                '<div class="btn turn-left btn-turnLeft"></div>',
                '<ul>',
                    '<li class="btn zoom-plus btn-zoomPlus" ></li>',
                    '<li class="btn zoom-moins btn-zoomMinus" ></li>',
                    '<li class="btn fullscreen btn-toggleFullScreen" ></li>',
                    '<li class="btn moving turn btn-toggleMove" ></li>',
                    '<li class="btn imprimer btn-print" ></li>',
                '</ul>',
                '<div id="legendes-control">',
                    '<span class="zoom">zoom</span>',
                    '<span class="fullscreen">plein écran</span>',
                    '<span class="moving turn">déplacer</span>',
                    '<span class="imprimer">Imprimer</span>',
                '</div>',
                '<div class="btn turn-right btn-turnRight"></div>',
            '</div>'*/

        ];
        _this.constructor.prototype.__init(player, conf, _this);
        _this._bindEvents();
        return _this;
    };



    this.initEvents = function() {
        //self.getPlayer().onEvent('onLoadMedia', function(nameMedia, nothing, joueur) { });
        var aBtn = $(self.getDom()).find('.btn').toArray();
        var btn;
        for (var cpt = 0; cpt < aBtn.length; cpt++) {
            btn = aBtn[cpt];
            var sFunction = $(btn).attr('class').match('btn-(.*)')[1];
            sFunction = '_' + sFunction;
            if (!self[sFunction] || typeof(self[sFunction]) !== 'function') {
                console.log('fonction "' + sFunction + '" n\'existe pas pour la palette controle');
            } else {
                self[sFunction](btn);
            }
        }

    };

    this._turnLeft = function(el) {
        var h = new Hammer(el, {prevent_default: true});
        h.onhold = function() {
            if (_mouseTimer) return;
            _mouseTimer = window.setInterval(function() {
                player.turnScene(-12);
            }, 60);
            return;
        };
        h.onrelease = function() {
            window.clearInterval(_mouseTimer);
            player.turnScene(-12);
            _mouseTimer = 0;
        };
    };

    this._turnRight = function(el) {
        var h = new Hammer(el, {prevent_default: true});
        h.onhold = function() {
            if (_mouseTimer) return;
            _mouseTimer = window.setInterval(function() {
                player.turnScene(12);
            }, 60);
            return;
        };
        h.onrelease = function() {
            window.clearInterval(_mouseTimer);
            player.turnScene(12);
            _mouseTimer = 0;
        };
    };

    this._zoomPlus = function(el) {
        var h = new Hammer(el, {prevent_default: true});
        h.onhold = function() {
            if (_mouseTimer) return;
            _mouseTimer = window.setInterval(function() {
                player.zoom(3);
            }, 60);
            return;
        };
        h.onrelease = function() {
            window.clearInterval(_mouseTimer);
            player.zoom(3);
            _mouseTimer = 0;
        };
    };

    this._zoomMinus = function(el) {
        var h = new Hammer(el, {prevent_default: true});
        h.onhold = function() {
            if (_mouseTimer) return;
            _mouseTimer = window.setInterval(function() {
                player.zoom(0.3);
            }, 60);
            return;
        };
        h.onrelease = function() {
            window.clearInterval(_mouseTimer);
            player.zoom(0.3);
            _mouseTimer = 0;
        };
    };

    this._fullscreen = function(el) {
        new Hammer(el, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
        .ontap = function() {
            player.toggleFullScreen();
            if (el.className.indexOf('back') >= 0) {
                $(el).removeClass('back');
            } else {
                $(el).addClass('back');
            }
        };
    };
    this._print = function(el) {
        new Hammer(el, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
        .ontap = function() {
            window.print();
        };
    };

    this._toggleMove = function(el) {
        new Hammer(el, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
        .ontap = function() {
            var possibleModes = ['turn', 'move'];
            $(el).removeClass(player.getSceneDragMode());
            var lautre = possibleModes[(0 + !possibleModes.indexOf(player.getSceneDragMode()))];
            $(el).addClass(lautre);
            player.setSceneDragMode(lautre);
        };
    };

    this._bindEvents = function() {
        self.getPlayer().onEvent('onReady', function(player) {
            self.render();
            self.show();
            if (player.getDrawMode() == 'flash') {
                $('.palette-control .btn-toggleMove').hide();
                var width = $('.palette-control').width() - 50;
                $('.palette-control').width(width);
            }
            self.setActiveDragMove();
            self.initEvents();
            return;
        });
    };

    this.__init(player, conf, this);
};




var PaletteEtages = function(player, conf) {
    var self = this;
    this.nbrEtages = 0;
    var EtagesDuplex = {};
    var activeClass = 'gradient-programme1';


    this.__init = function(player, conf, _this) {
        _this = _this || this;
        _this._aDom = [
            /*'<div id="paletteEtage" class="etages small palette palette-etage">' +
                '<h5>étages</h5>' +
                '<div class="etage-plus"></div>' +
                '<ul class="gradient2">' +
                '</ul>' +
                '<div class="etage-moins"></div>' +
                '<div class="pieds-palette">&nbsp;</div>' +
                '<div class="ombre"></div>' +
            '</div>'*/

            '<div class="palette-etage">' +
            //'<div class="aerien"><ul><li class="" rel=""></li></ul></div>' +
            //'<div class="etage-plus"></div>' +
            '<ul></ul>' +
            //'<div class="etage-moins"></div>' +
            //'<div class="pieton"></div>' +
            '</div>'
        ];
        _this.constructor.prototype.__init(player, conf, _this);
        this._bindEvents();
        return;
    };


    // fonction à définir
    this.goTo = function(target) {
            player.loadMedia(target);
            if (typeof(target) !== 'undefined') {
                $(this.getDom()).find('li').removeClass('active');
                $(this.getDom()).find('li[rel="' + target + '"]').addClass('active');
            }
            highlightProcess(player);
            player.doLayout();
    };


    this._initEvents = function() {
        var self = this;

        if (conf.isDuplex) {
            $(this.getDom()).find('li').each( function(){
                var that = this;
                new Hammer(this, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
                .ontap = function() {
                    var media = self.getPlayer().getCurrentMedia();
                    var duplex = parseInt($(that).attr("rel").replace('Etage', ''));
                    $(self.getDom()).find('li').removeClass('active ' + activeClass);
                    self.getPlayer().loadMedia(media, duplex);
                    $(that).addClass('active ' + activeClass);
                };
            });


        } else {
            $(this.getDom()).find('li.player-etage').each( function(){
                var that = this;
                new Hammer(this, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
                .ontap = function() {
                    $(self.getDom()).find('li.player-etage').removeClass('active ' + activeClass);
                    self.goTo($(that).attr("rel"));
                    $(that).addClass('active ' + activeClass);
                }
                /*.onhold = function() { $(that).addClass(activeClass); return true; }
                .onrelease = function() { $(that).removeClass(activeClass); return true; }*/;

                that.onmouseover = function() {$(that).addClass(activeClass);return true;};
                that.onmouseout  = function() {
                    if (that.className.indexOf('active') === -1) {
                        $(that).removeClass(activeClass);return true;
                    }
                };


            });

            var etageChange = $(this.getDom()).find('.etage-plus')[0];
            new Hammer(etageChange, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
            .ontap = function() {
                var newNode = $(self.getDom()).find('li.active').prev();
                if (!newNode || typeof(newNode.attr('rel')) === 'undefined') {
                    newNode = $(self.getDom()).find('li.player-etage').last();
                }
                $(self.getDom()).find('li').removeClass('active ' + activeClass);
                self.goTo(newNode.attr('rel'));
                newNode.addClass('active ' + activeClass);
            };


            etageChange = $(this.getDom()).find('.etage-moins')[0];
            new Hammer(etageChange, {prevent_default: true, tap_max_interval: 700, drag_vertical: false})
            .ontap = function() {
                var newNode = $(self.getDom()).find('li.active').next();
                if (!newNode || typeof(newNode.attr('rel')) === 'undefined') {
                    newNode = $(self.getDom()).find('li.player-etage').first();
                }
                $(self.getDom()).find('li').removeClass('active ' + activeClass);
                self.goTo(newNode.attr('rel'));
                newNode.addClass('active ' + activeClass);
            };
        }


        return;
    };




    this.doLayout = function() {
        /*var etages = $(this.getDom()).find('.etages li');
        var etage = etages.first();
        if(!etage) return;*/
        return this;
    };


    this.show = function() {
        $(self.getDom()).show();
        return self;
    };

    this.hide = function() {
        $(self.getDom()).hide();
        return self;
    };

    this._bindEvents = function() {
        var self = this;

        var buildEtagePalette = function() {
            self.render();
            /*var media = $(this).attr('class').match(new RegExp("media\\-([^ ]*)",'i'));
            if (media) {
                self._player.loadMedia(media[1]);
            }*/
            var etagesList = [], media = '', etageLabel, etageNumber, etagesSpeciaux = {};
            var data = player.getData('medias.mediasList');
            //console.dir(data);
            this.nbrEtages = 0;
            //console.log('chargement des étages');
            //var hasFoundDefault = false;
            var specialDefault = '', mediaLowerCase; //playerOptions.currentEtage;
            //var currentMedia = self.getPlayer().getCurrentMedia();
            for(var i in data) {
                media = i.toString();
                mediaLowerCase = media.toLowerCase();

                if(mediaLowerCase == 'aerien') {
                    specialDefault = 'aerien';
                    etagesSpeciaux[specialDefault] = {'media': media, label: 'Aérien'};

                } else if(mediaLowerCase == 'pieton') {
                    specialDefault = 'pieton';
                    etagesSpeciaux[specialDefault] = {'media': media, label: 'Piéton'};

                } else if(mediaLowerCase == 'rdc') {
                    specialDefault = 'rdc';
                    etagesSpeciaux[specialDefault] = {'media': media, label: 'Rdc'};

                } else if(mediaLowerCase == 'exterieur') {
                    specialDefault = 'exterieur';
                    etagesSpeciaux[specialDefault] = {'media': media, label: 'Aérien'};

                } else if (media.indexOf('Etage') >= 0) {
                    self.nbrEtages++;
                    etageNumber = media.replace('Etage', '');
                    etageLabel = etageNumber + '<span>ème</span>';
                    if (etageNumber == 0) {
                        etageLabel = 'Rdc';
                    } else if (etageNumber == 1) {
                        etageLabel = '1<span>er</span>';
                    }
                    etagesList[etageNumber] = {'media': media, label: etageLabel};
                }
            }

            var str = '';

            //console.dir(etagesList);
            //console.log('self.nbrEtages = ' + self.nbrEtages);
            var etageAerien = self.nbrEtages-2, aerien = etagesList[etageAerien];
            var etagePieton = self.nbrEtages-1, pieton = etagesList[etagePieton];
            //console.dir(pieton);
            //console.dir(aerien);

            if (etagesSpeciaux['aerien']) {
                etagesList.push(etagesSpeciaux['aerien']);
            } else {
            	aerien.label = 'Aerien';
            	etagesList[etageAerien] = null;
            	etagesList.push(aerien);
            }
            if (!etagesSpeciaux['pieton']) {
            	pieton.label = 'pieton';
            	etagesList[etagePieton] = null;
            }

            if (etagesSpeciaux['exterieur']) {
                etagesList.push(etagesSpeciaux['exterieur']);
            }
            etagesList.reverse();
            if (etagesSpeciaux['rdc']) {
                etagesList.push(etagesSpeciaux['rdc']);
            }

            if (etagesSpeciaux['pieton']) {
                etagesList.push(etagesSpeciaux['pieton']);
            } else {
            	etagesList.push(pieton);
            }



            //console.dir(etagesList);
            var currentMedia = self.getPlayer().getCurrentMedia();
            str += '<li class="etage-plus"><div></div></li>';
            for (var cpt in etagesList) {
            	if (!etagesList[cpt] || !etagesList[cpt].label) {
            		continue;
            	}
                str += '<li rel="' + etagesList[cpt].media + '" class="player-etage';
                if(etagesList[cpt].media === playerOptions.defaultMedia ){
                    str += ' active ' + activeClass;
                }
                str += '"><div>';
                str += etagesList[cpt].label;
                str += '</div></li>';
            }
            str += '<li class="etage-moins"><div></div></li>';
            $(self.getDom()).find('ul').html(str);
            self.doLayout();
            self.setActiveDragMove();
            self._initEvents();
            return;
        };


        var buildDuplexData = function() {
            EtagesDuplex = {};
            self.render();
            var data = player.getData('medias.mediasList');
            var i = '', j = '', listeEtages = [], listeLots = [];
            for (i in data) {
                if (data[i].zones) {
                    for (j in data[i].zones) {
                        if (typeof(EtagesDuplex[j]) !== 'undefined') {
                            EtagesDuplex[j]++;
                        } else {
                            EtagesDuplex[j] = 1;
                        }
                    }
                }
            }
            self.doLayout();
            self.setActiveDragMove();
        };


        var player = self.getPlayer();
        if (conf.isDuplex) {
            player.onEvent('onReady', buildDuplexData);

        } else {
            player.onEvent('onReady', buildEtagePalette);
        }

        player.onEvent('onLoadMedia', function(nameMedia, nothing, joueur) {
            if (conf.isDuplex) {
                if (typeof(EtagesDuplex[nameMedia]) !== 'undefined' && EtagesDuplex[nameMedia] > 1) {
                    var str = '';
                    var etageNumber = EtagesDuplex[nameMedia], etageLabel = '', actif = '';
                    while(etageNumber--) {
                        if (etageNumber == 0) {
                            etageLabel = 'Rdc';
                            actif = ' active';
                        } else if (etageNumber == 1) {
                            etageLabel = '1<span>er</span>';
                        }
                        str += '<li rel="Etage' + etageNumber + '" class="player-etage'
                        str += actif + '"><div>' + etageLabel + '</div></li>';
                    }
                    $(self.getDom()).find('ul').html(str);
                    self._initEvents();
                    self.show();

                } else {
                    self.hide();
                }


            } else {
                var zones = joueur.getData('medias.mediasList.' +  nameMedia + '.zones');
                if (!zones) {self.hide();return;}
                self.show();
            }

        });
    };

    this.__init(player, conf, this);
};



var PaletteLegends = function(player, conf) {
    var self = this;

    this.__init = function(player, conf, _this) {
        _this = _this || this;
        //_this.name = 'legends';
        //_this.__init(player, conf);

        _this._aDom = [
            /*'<div id="legendes" class="palette palette-legends">',
                '<div class="grip grip-gauche"></div>',
                '<div class="grip grip-droite"></div>',
                '<h5>Choix du type d\'appartement</h5>',
                '<div class="contenu-legendes content-legends">',
                '</div>',
                '<div class="ombre"></div>',
            '</div>'*/

            '<div id="legendes" class="palette-legends">',
               '<div class="content-legends">',
               '</div>',
            '</div>'
        ];
        _this.constructor.prototype.__init(player, conf, _this);
        this._bindEvents();
    };

    this.doLayout = function() {
        var jEl = $(self.getDom());
        var etage = $('.palette-etage');
        var position = parseInt(etage.css('top')) + etage.height() + 15;
        jEl.css('top', position + 'px');
        return this;
    };

    this.updateLegends = function() {
        var legendsCtn = $(self.getDom()).find('.content-legends')[0];
        var legends = self.getPlayer().getLegends();
        var currentMedia = self.getPlayer().getCurrentMedia();
        var mediasList = self.getPlayer().getData('medias.mediasList');
        var lots = self.getPlayer().getData('lots');
        var media = mediasList[currentMedia];

        if (!media || typeof media.zones === 'undefined' ) {
            $(self.getDom()).hide();
            return this;
        }
        var typesDispo = {};
        var statutsDispo = {};

        var aHtml = [];
        if (typeof media.zones !== 'undefined' && Object.keys(media.zones).length > 0) {
            for (var key in media.zones) {
                if (!media.zones.hasOwnProperty(key)) continue;
                var lot = lots[key];
                if (!lot) continue;
                typesDispo[lot.type] = true;
                statutsDispo[lot.statut] = true;
            }
        }

        var aTypesDispo, aStatutsDispo, style;
        aTypesDispo = Object.keys(typesDispo);
        aStatutsDispo = Object.keys(statutsDispo);

        if (aTypesDispo.length) {
            aTypesDispo.sort();
            //aHtml.push('<h3>Types</h3>');
            aHtml.push('<ul id="types-bloc">');
            var colorLegende;
            for (var cpt = 0; cpt < aTypesDispo.length; cpt++) {
                key = aTypesDispo[cpt];
                if(!(style = legends.type.values[key])) continue;
                //console.dir(legends.type.values[key].color);

                colorLegende = style.color + '';
                if (colorLegende.indexOf('#') < 0) {
                    colorLegende = parseInt(colorLegende);
                    colorLegende = '#' + colorLegende.toString(16);
                    //console.log('colorLegende = ' + colorLegende);
                }

                //aHtml.push('<li class="type" rel="' + key + '">' + key + '<div class="legend-sample type" style="background-color: ' + style.color + '"></div></li>');
                aHtml.push('<li class="type" rel="' + key + '"><div class="legend-sample" style="background-color: ' + colorLegende + '">' + key + '</div></li>');
            }
            aHtml.push('</ul>');
        } else {
            //console.log('pas de légendes (2)');
            $(self.getDom()).hide();
            return this;
        }
        /*if (aStatutsDispo.length) {
            aStatutsDispo.sort();
            //aHtml.push('<h3>Disponibilités</h3>');
            aHtml.push('<ul id="types-bloc-selecteur">');
            for (key in statutsDispo) {
                if(!(style = legends.statut.values[key])) continue;
                var label = parseInt(key) ? 'Disponible' : 'Non disponible';
                aHtml.push('<li class="dispo" rel="' + key + '">' + label + '<div class="legend-sample" style="background-color: ' + style.color + '"></div></li>');
            }
            aHtml.push('</ul>');
        }*/
        //console.log(aHtml);

        if (aHtml.length) {
            $(self.getDom()).show();
            legendsCtn.innerHTML = aHtml.join('');
            self.doLayout();
        } else {
            $(self.getDom()).hide();
        }
        return this;
    };

    function _createEventsLegends() {

        var player = self.getPlayer();
        //$('#legendes #types-bloc-selecteur li')
        var legendsEl = $(self.getDom()).find('.legend-sample');
        legendsEl.each(
                function() {
                var that = this.parentNode;
                new Hammer(this, {prevent_default: true,
                                                  tap_max_interval: 700, // seems to bee needed for IE8
                                                  drag_vertical: false})
                    .ontap = function(){
                    //console.log('clic sur un type de lot: "' + $(that).attr('rel') + '"');
                    opacityDefault = 0;
                    if( $(that).hasClass('disable') ){
                        $(that).removeClass('disable');
                        showTypeLot( $(that).attr('rel'), player );
                    } else {
                        $(that).addClass('disable');
                        hideTypeLot( $(that).attr('rel'), player );
                    }
                    //player.render();
                };
        });
        return null;
    };

    this._bindEvents = function() {
        self.getPlayer()
            .onEvent('onReady', function(player) {
                self.render();
            })
            .onEvent('onLoadMedia', function(nameMedia, nothing, joueur) {
                var zones = self.getPlayer().getData('medias.mediasList' + '.' + nameMedia + '.zones');
                if (!zones) {
                    self.hide();
                    return;
                } else {
                    self.updateLegends();
                    _createEventsLegends();
                    //self.show();
                    return;
                }
            });
    };
    this.__init (player, conf, this);
};

var PaletteToolTip = function(player, conf) {
    var self = this;
    var _currentZone = null;
    var _cacheZone = {};
    var _calmDownCpt = 0;
    var _zoneId;
    var _zoneData;
    //this.__init(player, conf);

    var _aTpl = ['<h5>{label}</h5>',
                '<div class="type">{type}</div>',
                '<div class="infos">',
                    '<span class="surface">{surface} m<sup>2</sup></span>',
                    '<span class="dispo">{statut}</span>',
                    '<span class="prix">{prix} €</span>',
                    //'<div class="visiter gradient-programme1">visiter</div>',
                '</div>',
                '<div class="pieds-palette">&nbsp;</div>',
                    '<div class="pointeur">&nbsp;</div>'

                /*'<div class="detailLot" >',
                    '<span class="label"></span>',
                    '<span class="value">{label}<span>',

                    '<span class="label"></span>',
                    '<span class="value">{type}<span>',
                '</div>'*/
                ];

    this.__init = function(player, conf, _this) {
        _this = _this || this;
        this._aDom = [
            '<div id="survol" class="palette-tooltip detailLot">',
                 /*'<div id="survol" class="palette" style="top: 50%; left: 50%;">',
                 '</div>',*/
                '<div class="pointeur spike"></div>',
            '</div>'
        ];

        //_this.name = conf.name || 'tooltip';
        //_this.parent.__init(player, conf, _this);
        _this.constructor.prototype.__init(player, conf, _this);
        this._bindEvents();
        return;
    };

    this.update = function(data) {
        //console.log('chargement des données');
        //console.dir(data);

        var tpl = _aTpl.join(' ');
        var str = tpl;
        data.statut = data.statut === 1 ? 'Disponible' : 'Non Dispo';
        switch (data.etage) {
           case 0 || "Rdc" || "rdc":;
               data.etageLabel = 'Rdc';
           break;
           case 1:;
               data.etageLabel = '1<sup>er</sup> étage';
           break;
           default:;
               data.etageLabel = new String(data.etage).toString() + '<sup>ème</sup> étage';
           break;
       }
       var typeLabel = data.type.slice(1);
       if ((typeLabel = parseInt(typeLabel) && typeLabel)) {
           data.typeLabel = typeLabel + ' pièce';
           data.typeLabel = typeLabel <= 1 ? typeLabel : data.typeLabel + 's'
       } else {
           data.typeLabel = '1 pièce';
       }

        for (var key in data) {
            if (!data.hasOwnProperty(key)) continue;
            var keyToFind = '{' + key +'}';
            while(str.search(keyToFind) !== -1) {
                str = str.replace(keyToFind, data[key]);
            }
        }

        if (data.prix <= 0) {
            str = str.replace(' class="prix"', ' class="prix cache"');
        } else {
            str = str.replace(' class="prix cache"', ' class="prix"');
        }

        return str;
    };


    function _show(zoneId, lot, mx, my) {
        var innerHTML;
        //var player = self.getPlayer();
        var toolTip = $(self.getDom());
        toolTip.stop(true, true);
        if (!lot) {return;}
        var playerPos = $(player.getDom()).offset();
        if (!playerPos) {
            playerPos = {top:0, left: 0};
        }

        //var canvas = toolTip.find('canvas');
        toolTip.css('top', (my - playerPos.top) + 'px'); // placement de la palette survol
        toolTip.css('left', (mx - playerPos.left) + 'px');
        if (typeof _cacheZone[zoneId] !== 'undefined') {
            innerHTML = _cacheZone[zoneId];
        } else {
            innerHTML = self.update(lot);
            _cacheZone[zoneId] = innerHTML;
        }
        toolTip.html(innerHTML);
        toolTip.show();

        var marginTop = $(self.getDom()).height() + 20;
        if (typeof(marginTop) === 'number') {
            $(self.getDom()).css('margin-top', '-' + marginTop + 'px');
        }
        _zoneId = zoneId;
        _zoneData = lot;
        return;
    };
   /**
     * position de la tooltip d'affichage d'info. Un tableau en 4 coordonnées [ position_left, position_left + width, position_top, position_left + height
     * @return Array
     **/
    function _getToolTipPosition() {
        var jEl = $(self.getDom());
        return [jEl.position().left, jEl.position().left + jEl.width(), jEl.position().top, jEl.position().top + jEl.height() + jEl.find('.spike').first().height()];
    };

    function _hide() {
        $(self.getDom()).fadeOut();
        self.getDom().removeAttribute('zoneId');
        return;
    };


    this.goTo = function(id) {
        var data = player.getData('lots.' + id);
        if (!data) {
            console.log('la lecture du lot "' + id + '" n\'a rien retourné');
        } else {
            player.loadMedia(id);
            player.resetScene();
        }
    };

    function _initEvents() {

        var h = (h = new Hammer(self.getDom())) ? h: new Hammer(self.getDom(), {tap_double: false, drag: false, tap: true});
        h.ontap = function(ev) {
            var data = _zoneData;
            if (data) {
                var id = data.id || data.label;
                self.goTo(id);
            }
        };
        return;
    }





    this._bindEvents = function() {

        self.getPlayer()
            .onEvent('onZoneSelected', function(data, zone, e) {
                var sZoneId = typeof zone === 'string' ? zone : zone.zoneId;
                if (self.getPlayer().getDrawMode() === 'flash') {
                    e = self.getPlayer().getMousePosition();
                }
                var v = player.getZoneCoordinates(zone, e);
                if (!self.getPlayer().isSceneDraging()
                    //&& !self.getPlayer().isStartDragedOnZone()
                    && data && data.label) {
                    _show(sZoneId, data, v.x, v.y);

                } else {
                    _hide();
                }
                return;
            })
            .onEvent('onZoneUnselected', function(data, zone, e) {
                _hide();
            })
            .onEvent('onReady', function(player) {
                self.render();
                _initEvents();
            })
            .onEvent('onSceneMove', function() {
               _hide();
            })
            .onEvent('onSceneRotate', function() {
               _hide();
            })
            .onEvent('onStartDragOnZone', function(data, zone, e) {
                self.getPlayer().disableSceneMove();
                var v = player.getZoneCoordinates(zone, e);
                _show(zone.zoneId, data, v.x, v.y);
            })


            .onEvent('onDragOnZone', function(data, zone, startZoneData, startZone, e) {
                _calmDownCpt++;
                if(!zone || !data) {
                    _hide();
                } else if (zone.zoneId !== startZone.zoneId) {
                    if (0 === _calmDownCpt % 2) {return;}
                    var v = player.getZoneCoordinates(zone, e);
                    _show(zone.zoneId, data, v.x, v.y);
                }

            })
            .onEvent('onEndDragOnZone', function(data, zone, e) {
                self.getPlayer().enableSceneMove();
            })
            .onEvent('onLoadMedia', function() {
                _hide();
            });

        return;
    };

    this.__init(player, conf, this);
};

var MiniLoading = function(player, conf) {
    var self, _miniloadingToAnim;
    self = this;

    var _timeoutRotation;
    var _target;


    //class="maquette-miniloader"
    this.__init = function(player, conf, _this) {
        _this = _this || this;
        this._aDom = [
            '<div class="palette-miniloading" style="z-index: 2000">',
            '<div class="maquette-miniloading-anim">',
            '</div>',
            '</div>'
            /*'<div id="maquette-miniloader" style="z-index: 2000">',
                '<div id="maquette-miniloader-anim">',
                '</div>',
            '</div>'*/
        ];
        //_this.name = conf.name || 'miniloading';
        //_this.parent.__init(player, conf, _this);
        _this.constructor.prototype.__init(player, conf, _this);
        this._bindEvents();
        return;
    };





            /*_target = conf.target;
        _dom = document.createElement('div');
        _miniloadingToAnim = document.createElement('div');
        _miniloadingToAnim.setAttribute('id', 'maquette-miniloader-anim');
        _dom.appendChild(_miniloadingToAnim);
        _dom.setAttribute('id', 'maquette-miniloader');*/

    function _startRotation() {

        return;

        /*if (!_miniloadingToAnim) {
            return false;
        }
        var jEl = $(_miniloadingToAnim);
        var nb = 0;
        _timeoutRotation = window.setInterval(function() {
            jEl.css('-webkit-transform','rotate('+ nb + 'deg)');
            jEl.css('-moz-transform','rotate('+ nb + 'deg)');
            nb+=20;
            nb = nb >= 360 ? 0 : nb;
        },80);
        return;*/
    };

    function _stopRotation() {
        if (!_timeoutRotation) return false;
        window.clearInterval(_timeoutRotation);
        _timeoutRotation = null;
        return true;
    };

    /*this.render = function() {
        //_target.appendChild(_dom);
        //document.body.appendChild(_dom);
        $(self.getDom()).css('z-index', 2000);
        _isRender = true;
        return this;
    };*/

    this.show = function( target ) {
        if (!this.isRender()) {
            return this;
        }
        if (!_target) {
            if( target ){
                _target = target;
            }else {
                _target = document.body;
            }
        }

        self.getDom().style.display = 'block';
        _startRotation();
        return this;
    };

    this.hide = function() {
        if (!this.isRender()) return this;
        self.getDom().style.display = 'none';
        _stopRotation();
        return this;
    };


    this._bindEvents = function() {
        _target = self.getPlayer().getDom();
        $(function() {
            self.render();
            _miniloadingToAnim = self.getDom().getElementsByTagName('div')[0];
            self.show();
        });
        self.getPlayer()
            .onEvent('onContainerRender', function(player) {
                if (!_miniloadingToAnim) {
                    var a = self.getDom();
                    if (a) {
                        _miniloadingToAnim = self.getDom().getElementsByTagName('div')[0];
                    }
                }
                //self.show();
            })
            .onEvent('onChangeMedia', function() {
                self.show();
            })
            .onEvent('onImgsDownloadComplete', function() {
                //console.log('complete', self.getPlayer().getPlayerId());
                self.hide();
            });
            return;
    };
    this.__init(player, conf, this);
};

var PaletteCompass = function(player, conf) {
    var self;
    self = this;
    var _northFrame = 0;
    var _base12 = [0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 168, 180, 192, 204, 216, 228, 240, 252, 264, 276, 288, 300, 312, 324, 336, 358, 360];
    var _defaultFrameBase = 12;

    this.__init = function(player, conf, _this) {
        _this = _this || this;
        _this._aDom = [
            '<div id="orientation" class="palette-compass">',
                '<h5>orientation</h5>',
                '<div id="boussole">',
                '</div>',
                '<div class="pieds-palette">&nbsp;</div>',
            '</div>'
        ];

       // _this.name = conf.name || 'compass';
        //_this.parent.__init(player, conf, _this);
        _this.constructor.prototype.__init(player, conf, _this);
        _this._bindEvents();
        return;
    };

    this.setSize = function (width, height) {
        if (width) {
            $(self.getDom().width(width));
        }

        if (height) {
            $(self.getDom().height(height));
        }
        return self;
    };

    this.setNorthFrame = function(northFrame) {
        _northFrame = parseInt(northFrame);
        return self;
    }

    this.setPosition = function(obj) {
        obj = obj || {};
        if (obj.top) {
            $(self.getDom()).css('top', obj.top);
        } else if (obj.bottom) {
             $(self.getDom()).css('bottom', obj.bottom);
        }

        if (obj.left) {
             $(self.getDom()).css('left', obj.left);
        } else if (obj.right) {
             $(self.getDom()).css('right', obj.right);
        }
        return self;
    };

    this.show = function() {
        $(self.getDom()).show();
        return self;
    };

    this.hide = function() {
        $(self.getDom()).hide();
        return self;
    };

    /**
     * retourne l'élément de la palette qui va subir la rotation
     * @return DomNode
     **/
    this.getRotateElDom = function() {
        return $(self.getDom()).find('img').first()[0];
    };

    function _findMyDegree (f, base) {
    for (var cpt = 0; cpt < 360; cpt += base) {
        if (cpt > f) {
            var diffMinus = f - (cpt -12);
            var diffPlus = cpt - f;

            if (diffMinus < diffPlus) {
                return cpt -12;
            } else {
                return cpt;
            }
        }
        }
        return null;
    };

    this.rotate = function(degree) {
        if (self.getPlayer().isHTML5()) {
            var strRotate = 'rotate(' + (degree /*-1*/) + 'deg)';
            var rotateBrowser = ['-webkit-transform', 'transform', '-moz-transform', '-o-transform'];
            for (var cpt = 0; cpt < rotateBrowser.length; cpt++) {
                $(self.getRotateElDom()).css(rotateBrowser[cpt], strRotate);
            }
        } else {
            if (_base12.indexOf(degree) === -1) {
                degree = _findMyDegree(degree, _defaultFrameBase);
                if (degree === null) {return;}
            }
            self.getRotateElDom().src = 'img/compass/compass_' + degree + '.png';
        }
        //$(self.getDom()).css('-webkit-transform', strRotate);
        return self;
    };

    this.updateCurrentFrame = function(curFrame) {
        self.rotate(self.processDegree(curFrame, self.getPlayer().getFps()));
        return self;
    };

    this.processDegree =function(curFrame, maxFrame) {
        return (360 * (curFrame - _northFrame)) / maxFrame;

    };


    this._bindEvents = function() {
        /*$(function() {
            /*self.render();
            _miniloadingToAnim = self.getDom().getElementsByTagName('div')[0];
            self.show();
        });*/
        self.getPlayer()
            .onEvent('onContainerRender', function(player) {
                self.render();
                //self.setActiveDragMove();
                var img = document.createElement('img');
                img.src = self.getConf().img;
                //$(self.getDom()).css('position', 'absolute').css('z-index', 1);
                //$(self.getDom()).css('display', 'block');
                //$(self.getDom()).width(60).height(60);
                $(self.getDom()).find('#boussole')[0].appendChild(img);
            }).onEvent('onSceneRotate', function(newFrame, oldFrame, factor, duration, joueur) {
                //console.log('event rotation palette', newFrame, oldFrame, factor);
                //console.log('rotate', newFrame, oldFrame, factor);
                if (newFrame !== oldFrame) {
                    self.updateCurrentFrame(newFrame);
                }
            }).onEvent('onLoadMedia', function() {
                self.updateCurrentFrame(self.getPlayer().getCurrentFrame());
            });
            return;
    };

    this.init = function() {
        //self.init();
        _northFrame = conf.northFrame ? conf.northFrame : _northFrame;
    }();

    this.__init(player, conf, this);
};

var PaletteMiniMaquette = function(player, conf) {
    var self = this;
    var _miniPlayer;
    var _etage = null;
    var _mediasList = null;
    var _imgs = [];
    var _isEnable = false;
    var _currentLot;

    var _baseWidth = 200;
    var _baseHeight = 0;

    var _image;

    this.loadMedia = function(media) {
        var img = self.getPlayer().loadMediaImgs(media);
        _imgs = img;
        return;

    };

    this.loadFrame = function(frame) {
        var currentFrame = frame || self.getPlayer().getCurrentFrame();
        if (typeof _imgs[currentFrame] !== 'undefined') {
            _image.src = _imgs[currentFrame].src;
            this.doLayout();
        }
        return this;
    }

    this.doLayout = function() {
        //var rapport = $(_image).width() / $(_image).height();
        //_baseHeight = $(_image).height() * _baseWidth / $(_image).width();
        //$(self.getDom()).width(_baseWidth).height(_baseHeight);
        self.getMiniPlayer().doLayout();
        return this;
    };

    this.enable = function() {
        /*var timeoutcheck = window.setInterval(function() {
            if (self.getMiniPlayer().isReady() && self.getMiniPlayer().isSceneReady()) {
                var navList = self.getPlayer().getNavigationList();
                _miniPlayer.loadMedia(navList[navList.length -2]);
                window.setTimeout(function() {
                    _miniPlayer.highlightZones([_currentLot], 0);
                    window.clearInterval(timeoutcheck);
                }, 200);
            }
        }, 40);*/
        _isEnable = true;
        return this;
    };

    this.isEnabled = function() {
        return _isEnable;
    };

    this.disable = function() {
        _isEnable = false;
        return this;
    };

    this.getContainer = function() {
        return $(self.getDom()).find('.miniplayer-container')[0];
    };

    this.getMiniPlayer = function() {

        if (!_miniPlayer) {
            //console.log('_miniPlayer n\'existe pas (vraiment)');

            // config clonée du player principal
            var mainPlayer = self.getPlayer();
            var conf = mainPlayer.getBaseConfig();
            conf.definition = 'jpg-450';
            conf.scale3d = .5;
            conf.target = self.getContainer().getAttribute('id');
            /*if (mainPlayer.isReady()) {
                conf.jsonMediasData = mainPlayer.getData('medias');
                conf.jsonLotsData = mainPlayer.getData('lots');
            }*/
            /*conf.enableLoadMedia = */conf.enableDragScene =  conf.enableCheckZone = false;
            conf.startFrame = mainPlayer.getCurrentFrame();
            var navList = self.getPlayer().getNavigationList();
            conf.defaultMedia = _etage; //navList[navList.length -2];
            /*conf.forceFlashMode = true;*/
            conf.canvasWidth = $('#' + conf.target).width();
            conf.canvasHeight = $('#' + conf.target).height();

            //console.log('création du _miniPlayer');
            _miniPlayer = new Player(conf);
            _miniPlayer.onEvent('onImgsDownloadComplete', function() {
                //console.log('fin du chargement des images du miniplayer');
                if (!self.isEnabled()) return;
                self.doLayout();
                _miniPlayer.highlightZones([_currentLot], 0);
            });


        } else {
            //console.log('_miniPlayer existe finalement');
            _miniPlayer.highlightZones([_currentLot], 0);
        }
        return _miniPlayer;
    };

    this._bindEvents = function() {
        var player = self.getPlayer();

        player.onEvent('onReady', function() {
            self.render();
            //console.log('minimaquette onReady()');
            // -- toggle de la palette
            refreshCollapseAction($(self.getDom()));
            /*
            $(self.getDom()).find('.toggle-size').click(function() {
                $(self.getDom()).find('.toggle-container').toggle('slow');
                if (this.className.indexOf('toggle-reduce') >= 0) {
                    this.className = "toggle-size";
                } else {
                    this.className = "toggle-size toggle-reduce";
                }
            });*/
            self.setActiveDragMove();

            //self.hide();

            _mediasList = self.getPlayer().getData('medias.mediasList');
            //_image = $(self.getDom()).find('.container')[0];
        })
        .onEvent('onLoadMedia', function(name, none, joueur) {
            var key, keyZone;
            _etage = null;
            name = name.toString();
            _currentLot = name;
            //console.log('minimaquette onLoadMedia(), name = ' + name);
            var etage;
            for (key in _mediasList) {
                etage = _mediasList[key];
                if (etage.zones) {
                    for (keyZone in etage.zones) {
                        //console.log('test de ' + name + ' et keyZone=' + keyZone);
                        if (keyZone === name) {
                            self.enable();
                            self.show();
                            //console.log('lot trouvé, etage = ' + key);

                            _etage = key;
                            var miniPlayer;
                            if(!_miniPlayer) {
                                miniPlayer = self.getMiniPlayer();
				miniPlayer.gotoFrame(self.getPlayer().getCurrentFrame());

                            } else {
                                //console.log('_miniPlayer existe, on affiche le lot en cours');
                                var miniPlayer = self.getMiniPlayer();
                                miniPlayer.goToFrame(self.getPlayer().getCurrentFrame());
                                //var navList = self.getPlayer().getNavigationList();
                                miniPlayer.loadMedia(key); // navList[navList.length -2]
                            }

                            return;
                        }
                    }
                }
            }
            self.disable();
            self.hide();
            return;
        })

        .onEvent('onSceneRotate', function(newFrame, oldFrame, speed, duration, joueur) {
            //console.dir(arguments);
            if (!_miniPlayer ||  false === self.isEnabled()) return;
            _miniPlayer.gotoFrame(newFrame);
        });
        return;
    };

    this.__init = function(player, conf, _this) {
        _this = _this || this;
        _this._aDom = [
            '<div  class="palette-mini-maquette">',
                '<h5></h5>',
                //'<div class="grip grip-gauche"></div>',
                '<div class="toggle-container">',
                    '<div id="palette-minimaquette" style="width: 100%;" class="miniplayer-container container"></div>',
                '</div>',
                //'<div class="grip grip-droite"></div>',
                '<div class="toggle-size toggle-reduce"></div>',
            '</div>'
        ];

       // _this.name = conf.name || 'compass';
        //_this.parent.__init(player, conf, _this);
        _this.constructor.prototype.__init(player, conf, _this);
        _this._bindEvents();
        //self.getMiniPlayer();
        return;
    };

    this.show = function() {
        $(self.getDom()).show();
        return self;
    };

    this.hide = function() {
        $(self.getDom()).hide();
        return self;
    };

    this.init = function() {

    }();

    this.__init(player, conf, this);
};

var PaletteInformationsLot = function(player, conf) {
    var self = this;
    var _currentData;
    var _currentMedia;

    var _aTpl = [
        '<h5>lot {label}</h5>',
        '<div class="infos">',
        '<div class="infosDetails bloc">',
             '<h4 class="logement"><span></span>votre appartement</h4>',

             '<div class="bloc_details">',
                 '<div class="version-pc">',
                     '<h3 class="type">{typeLabel}</h3>',
                     '<p class="dispo">{statut}</p>',
                     '<hr />',
                     '<h3 class="titre_surface">Surface habitable</h3>',
                     '<h2 class="surface">{surface} m<sup>2</sup></h2>',
                     '<h3 class="etage">{etageLabel}</h3>',
                     '<div class="bloc bloc_prix">',
                         ' <h3 class="prix"><span class="label">prix TVA 19.6%</span> <span class="value">{prix} €</span></h3>',
                         ' <hr />',
                         '<ul class="liste">',
                             '<li>',
                                 '<p>Prix TTC cave et parking(s) inclus(*)</p>',
                                 '<p>* 1 place de parking du studio au {typeLabel}<br />* 2 places de parking</p>',
                             '</li>',
                         '</ul>',
                     '</div>',
                 '</div>',


                 '<div class="version-ipad">',
                    '<div class="infos-col1">',
                         '<h3 class="type">{typeLabel}</h3>',
                         '<h3 class="prix"><span class="value">{prix} €</span></h3>',
                         '<span class="label">prix TVA 19.6%</span>',
                         '<p class="dispo {statutClasse}">{statut}</p>',
                         '<h3 class="etage">{etageLabel}</h3>',
                         '<h2 class="surface">{surface} <span>m<sup>2</sup></span></h2>',
                     '</div>',

                     /*'<div class="infos-col1">',
                     '</div>',

                     '<div class="infos-col2">',
                     '</div>',*/

                     '<div class="bloc bloc_prix">',
                         /*'<ul class="liste">',
                             '<li>',
                                 '<p>Prix TTC cave et parking(s) inclus(*)</p>',
                                 '<p>* 1 place de parking du studio au {typeLabel} pièces<br />* 2 places de parking</p>',
                             '</li>',
                         '</ul>',*/
                     '</div>',
                 '</div>',
             '</div>',

         '</div>',
         '<div class="bloc bloc_document">',
            '<h4 class="document reduit"><span></span>téléchargement</h3>',
                '{listeDocs}',
         '</div>',
         '<div class="button gradient3 boutonRecevoirDossier">Recevoir un dossier</div>',
         '<div class="button gradient3 boutonDemandeContact">Demande de contact</div>',
        '<div class="pieds-palette">&nbsp;</div>'
     ];


    this.__init = function(player, conf, _this) {
        _this = self;
        _this._aDom = [
            '<div class="infosLot palette-informations-lot">',
                                '<div class="grip grip-gauche"></div>',
                                '<div class="grip grip-droite"></div>',
                                '<div class="toggle-size toggle-reduce"></div>',
                '<div class="ficheLot"></div>',
            '</div>'
        ];

       // _this.name = conf.name || 'compass';
        //_this.parent.__init(player, conf, _this);
        _this.constructor.prototype.__init(player, conf, _this);
        _this._bindEvents();
    }


    /**
     * insert une string dans le container de la palette
     * @return void
     */
    function _insertStr(str) {
        $(self.getDom()).find('.ficheLot').html(str);
        return;
    };

    this.applyUpdate = _insertStr;

    this._bindEvents = function() {
        self.getPlayer().onEvent('onLoadMedia', function(nameMedia, nothing, joueur) {
            var dataLot = joueur.getData('lots.' + joueur.getCurrentMedia());
            if(!dataLot) {
                self.hide();
                return;
            }
            if (!self._isRender) {
                self.render();
                self.setActiveDragMove();
                refreshCollapseAction($(self.getDom()));
            }

            self.setCurrentData(dataLot).setCurrentMedia(nameMedia);
            var str = self.update(dataLot);
            _insertStr(str);
            refreshInfosLotEvents();
            if (typeof dataLot.documents !== 'undefined' && dataLot.documents.length > 0) {
                $('#maquette .infosLot .bloc_document').show();
            } else {
                $('#maquette .infosLot .bloc_document').hide();
            }
            self.show();
            return;
        });

    };

    this.setCurrentMedia = function(name) {
        _currentMedia = name;
        return this;
    };

    this.setCurrentData = function(data) {
        _currentData = data;
        return this;
    };



    this.update = function(data) {
        var tpl = _aTpl.join(' ');
        var str = tpl;
        data.statutClasse = data.statut === 1 ? '' : 'non-dispo';
        data.statut = data.statut === 1 ? 'Encore disponible' : 'Non Dispo';

        switch (data.etage) {
           case 0 || "Rdc" || "rdc":;
               data.etageLabel = 'Rdc';
           break;
           case 1:;
               data.etageLabel = '1<sup>er</sup> étage';
           break;
           default:;
               data.etageLabel = new String(data.etage).toString() + '<sup>ème</sup> étage';
           break;
       }
       var typeLabel = data.type.slice(1);
       if ((typeLabel = parseInt(typeLabel) && typeLabel)) {
           data.typeLabel = typeLabel + ' pièce';
           data.typeLabel = typeLabel <= 1 ? typeLabel : data.typeLabel + 's'
       } else {
           data.typeLabel = '1 pièce';
       }

        if (typeof data.documents !== 'undefined' && data.documents.length > 0) {
            var aListeHTML=  ['<ul class="liste">'];
            var currentDoc;
            for (var cpt = 0; cpt < data.documents.length; cpt++) {
                currentDoc = data.documents[cpt];

                if (currentDoc.src.indexOf('http://') < 0) {
                    currentDoc.src = self.getPlayer().getBaseUrl() + _currentMedia + '/documents/' + currentDoc.src;
                }

                aListeHTML.push('<li><a href="' + currentDoc.src + '" target="_blank">' +  currentDoc.label + '</a></li>');
            }
            aListeHTML.push('</ul>')
            data.listeDocs = aListeHTML.join("\r\n");

        } else {
            data.listeDocs = ''; //'<div class="no-docs">Aucun document</div>';
        }

        for (var key in data) {
            if (!data.hasOwnProperty(key)) continue;
            var keyToFind = '{' + key +'}';
            while(str.search(keyToFind) !== -1) {
                str = str.replace(keyToFind, data[key]);
            }
        }

        return str;
	}


    this.__init(player, conf, self);
};

// --extends PalettePlayer
PalettePlayer.extending([
    PaletteControls,
    PaletteEtages,
    PaletteLegends,
    PaletteToolTip,
    MiniLoading,
    PaletteCompass,
    PaletteMiniMaquette,
    PaletteInformationsLot
]);